﻿global using Newtonsoft.Json;
global using Newtonsoft.Json.Linq;
global using System.Data;
global using System.Data.SqlClient;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.Caching;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace ztymodbus
{



    internal class Code
    {



        Conn conn = new();
        public void Into_Blog(string content, int adduser, string Table_Name, int Table_ID)
        {
            //NLog_Into(adduser + ": " + content + "|||" + Table_Name + "|||" + Table_ID + "|||");

            SqlParameter[] Par = new SqlParameter[] { new SqlParameter("@adduser", adduser) };
            IDataReader dr = conn.SelectSql(" SELECT top 1 Staff_Name FROM [staff]  WITH(UPDLOCK)  where id=@adduser ", Par);
            if (dr.Read())
            {
                string Staff_Name = dr["Staff_Name"].ToString();

                SqlParameter[] Par2 = new SqlParameter[] {
                    new SqlParameter("@Staff_Name", Staff_Name) ,
                    new SqlParameter("@content", content) ,
                    new SqlParameter("@Table_Name", Table_Name) ,
                    new SqlParameter("@Table_ID", Table_ID) ,
                    new SqlParameter("@adduser", adduser) ,
                    new SqlParameter("@AddIP", "{\"ip\":\"127.0.0.1\"}") ,
                };

                //删除日志表中大于200天的日志记录；
                using (SqlConnection cnn = new SqlConnection(Conn.ConnString()))
                {
                    cnn.Open();
                    //SqlParameter[] sp = null;
                    using (SqlCommand comm = new SqlCommand("Delete [Blog]  WITH(UPDLOCK) where datediff(day,addtime,getdate())>=200", cnn))
                    {
                        //comm.Parameters.AddRange(Par);
                        //SqlDataReader dr = comm.ExecuteReader();
                        int i = comm.ExecuteNonQuery();
                        comm.Parameters.Clear();
                        comm.Dispose();
                    }

                    using (SqlCommand comm = new SqlCommand("select top 1 * from [Blog] WITH(UPDLOCK)  where [Table_Name]=@Table_Name and  [Table_ID]=@Table_ID and  [content]=@content and  [adduser]=@adduser and  [AddIP]=@AddIP  and datediff(minute,addtime,getdate())<60 order by id desc", cnn))

                    {
                        comm.Parameters.AddRange(Par2.Select(x => ((ICloneable)x).Clone()).ToArray());
                        SqlDataReader dr2 = comm.ExecuteReader();
                        if (!dr2.Read())
                        {
                            using (SqlCommand comm2 = new SqlCommand("  insert into [Blog]  WITH(UPDLOCK)  ([Table_Name],[Table_ID],[content],[adduser],[AddIP]) values(@Table_Name,@Table_ID,@content,@adduser,@AddIP)  ", cnn))
                            {
                                comm2.Parameters.AddRange(Par2.Select(x => ((ICloneable)x).Clone()).ToArray());
                                //SqlDataReader dr = comm.ExecuteReader();
                                int i2 = comm2.ExecuteNonQuery();
                                comm2.Parameters.Clear();
                                comm2.Dispose();
                            }
                        }

                        comm.Parameters.Clear();
                        comm.Dispose();
                    }






                }

            }

        }

        public string Get_Config(string Field)
        {


            string temp = "";



            ObjectCache _cache = System.Runtime.Caching.MemoryCache.Default;

            string cacheKey = "config";
            DataSet dataSet = new DataSet();

            if (_cache.Contains(cacheKey))
            {
                dataSet = (DataSet)_cache.Get(cacheKey);
                // 如果缓存中存在
                //Console.WriteLine("从缓存中获取");
                //code.Into_Blog("MyMemoryCache 从缓存中获取", 1, "Staff",1);
            }
            else
            {

                using (DbConnection con = new SqlConnection(Conn.ConnString()))
                {
                    con.Open();
                    using (DbCommand com = con.CreateCommand()) // new SqlCommand(sql, con)
                    {
                        string sql = "select * from [config]  WITH(UPDLOCK)  order by id desc";
                        com.CommandText = sql;
                        using (DbDataAdapter sda = new SqlDataAdapter((SqlCommand)com))  // new SqlDataAdapter(com)
                        {
                            using (dataSet = new DataSet(cacheKey))
                            {
                                sda.Fill(dataSet);
                            }
                            com.Parameters.Clear();
                        }
                    }

                }

                // 创建缓存策略，这里使用相对过期
                TimeSpan cacheDuration = TimeSpan.FromMinutes(60);
                DateTimeOffset dateTimeOffset = DateTimeOffset.Now.Add(cacheDuration);
                CacheItemPolicy policy = new CacheItemPolicy
                {
                    SlidingExpiration = cacheDuration // cacheDuration 是 TimeSpan 类型
                };
                // 将 DataSet 存入缓存
                _cache.Remove(cacheKey); // 先移除旧的缓存项（如果存在）
                _cache.Add(cacheKey, dataSet, policy);
            }

            try
            {
                DataTable productsTable = dataSet.Tables[0];
                DataRow[] selectedRows = productsTable.Select(" name='" + Field + "'  ");
                foreach (var dr in selectedRows)
                {
                    temp = dr["value"].ToString();
                }
            }
            catch (Exception ex)
            {
                temp = ex.ToString();
            }



            return temp;
        }


        //读取用户表STAFF 生成 JSON数组 jarray 

        public JArray get_staff_uuid()
        {
            JArray json_array = new();


            IDataReader dr = conn.SelectSql("SELECT id,uuid,staff_name FROM [Staff] WITH(UPDLOCK) where staff_status=100 ");
            while (dr.Read())
            {
                JObject json_item = new();
                string uuid = dr["uuid"].ToString();
                string staff_name = dr["staff_name"].ToString();

                json_item.Add("uuid", uuid);
                json_item.Add("staff_name", staff_name);

                json_array.Add(json_item);


            }

            //其他部分在JSON文件中
            try
            {
                string ServiceAddress = "location_staff_uuid.json";  //本地路径文件名
                StreamReader sr = new StreamReader(ServiceAddress);
                string retString = sr.ReadToEnd();  // 读取全文本
                sr.Close();

                //对读取的内容处理
                JArray list = JArray.Parse(retString);

                for (int i = 0; i < list.Count; i++)
                {
                    JObject json_item = new();
                    string uuid = list[i]["uuid"].ToString();
                    string staff_name = list[i]["staff_name"].ToString();
                    json_item.Add("uuid", uuid);
                    json_item.Add("staff_name", staff_name);
                    json_item.Add("papers", list[i]["papers"].ToString());
                    json_item.Add("idCard", list[i]["idCard"].ToString());
                    json_item.Add("telephone", list[i]["telephone"].ToString());
                    json_item.Add("staffGender", list[i]["staffGender"].ToString());
                    json_item.Add("createDate", list[i]["createDate"].ToString());
                    json_item.Add("createBy", list[i]["createBy"].ToString());
                    json_item.Add("affiliation", list[i]["affiliation"].ToString());
                    json_item.Add("deleted", list[i]["deleted"].ToString());
                    json_array.Add(json_item);
                }
            }
            catch (Exception ex)
            {
                JObject json_item = new();
                json_item.Add("ex", ex.ToString());
                json_array.Add(json_item);
                //Result.Text = ex.ToString();
            }

            return json_array;

        }

        public Boolean IsNumber(string _s)
        {
            double ResultNum;
            Boolean _i = double.TryParse(_s, out ResultNum);
            return _i;
        }

        public int MakeRand(int start, int end)
        {
            Random ran = new Random(Math.Abs(Guid.NewGuid().GetHashCode()));
            int RandKey = ran.Next(start, end);   //生成100-999随机数字
            return RandKey;
        }

        public string Get_Staff_Open_ID(int id)
        {
            string temp = "";
            if (id > 0)
            {
                SqlParameter[] sp = new SqlParameter[]
                    {
                  new SqlParameter("id",id),
                    };
                IDataReader dr = conn.SelectSql(" select top 1 id, Open_ID from [Staff] WITH(UPDLOCK) where [id]=@id ", sp);
                if (dr.Read())
                {
                    temp = dr["Open_ID"].ToString();
                }
                dr.Close();
            }

            return temp;
        }


        public (string opend_id, string staff_name) Get_Staff_Open_ID_name(int id)
        {
            string open_id = "";
            string staff_name = "";
            if (id > 0)
            {
                MyMemoryCache myMemoryCache = new MyMemoryCache();
                DataTable dt = myMemoryCache.get_staff();
                DataRow[] selectedRows = dt.Select("Staff_Status = 100 AND ID =" + id);
                foreach (var dr in selectedRows)
                {
                    open_id = dr["open_id"].ToString();
                    staff_name = dr["staff_name"].ToString();
                    //Console.WriteLine(row["Staff_Name"].ToString());
                }

            }


            return (open_id, staff_name);
        }

        public bool PingIP(string DoNameOrIP)
        {
            try
            {
                Ping objPingSender = new Ping();
                PingOptions objPinOptions = new PingOptions();
                objPinOptions.DontFragment = true;
                string data = "";
                byte[] buffer = Encoding.UTF8.GetBytes(data);
                int intTimeout = 120;
                PingReply objPinReply = objPingSender.Send(DoNameOrIP, intTimeout, buffer, objPinOptions);
                string strInfo = objPinReply.Status.ToString();
                //Thread.Sleep(100);

                if (strInfo == "Success")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }

        }

        public static readonly Lock o_into_alarm = new Lock();
        public void into_alarm(string name, string content, string send_staff, DateTime add_time, ArrayList array = null)
        {
            lock (o_into_alarm)
            {
                _ = Task.Run(() =>
                {
                    try
                    {
                        send_staff = send_staff + ",,,";
                        string[] Send_WX_Staff_ID = send_staff.Split(",");
                        foreach (string id in Send_WX_Staff_ID)
                        {
                            if (IsNumber(id))
                            {
                                send_staff += Get_Staff_Open_ID_name(id.ToInt()).staff_name + ",";
                            }
                        }


                        List<SqlParameter> list_SP = new();
                        list_SP.Add(new SqlParameter("id", Guid.CreateVersion7()));
                        list_SP.Add(new SqlParameter("name", name));
                        list_SP.Add(new SqlParameter("content", content));
                        list_SP.Add(new SqlParameter("send_staff", send_staff));
                        list_SP.Add(new SqlParameter("add_time", add_time));

                        SqlParameter[] sp = list_SP.ToArray();

                        IDataReader dr = conn.SelectSql("select top 1 * from [Alarm_iot_list]  WITH(UPDLOCK) where [name]=@name and [content]=@content and datediff(minute,add_time,getdate())<10 and [status]=1 order by id desc", sp);
                        if (!dr.Read())
                        {
                            conn.InsertSql_uuid(" insert into [Alarm_iot_list]  WITH(UPDLOCK) ([id],[name],[content],[send_staff],[add_time]) values(@id , @name , @content , @send_staff , @add_time )  ", sp);
                        }
                    }
                    catch (Exception ex)
                    {
                        Into_Blog("写入报警日志出错:" + ex.ToString() + "<br/><br/>name:" + name + "<br/>content:" + content + "<br/>send_staff:" + send_staff + "<br/>add_time:" + add_time, 1, "Alarm", 0);
                    }
                });
            }

        }


        public static readonly Lock o_wx = new Lock();


        public string Into_Notice_WX(HttpClient client ,string First, string type, string Keyword1, string Keyword2, string Keyword3, string Remark, string Url, string MB_ID, int To_Staff_ID, string Keyword4 = "")
        {

            string result = "";
            //string mbid = FromJson["mbid"].ToString();
            //string staff_id = FromJson["staff_id"].ToString() + ",";
            //string keyword1 = FromJson["keyword1"].ToString();
            //string keyword2 = FromJson["keyword2"].ToString();
            //string keyword3 = FromJson["keyword3"].ToString();
            //string keyword4 = FromJson["keyword4"].ToString();
            //string url = FromJson["url"].ToString();


            //List<DbParameter> list_SP = new();
            //list_SP.Add(new SqlParameter("Keyword1", Keyword1));
            //list_SP.Add(new SqlParameter("Keyword2", Keyword2));
            //list_SP.Add(new SqlParameter("Keyword3", Keyword3));
            //list_SP.Add(new SqlParameter("Keyword4", Keyword4));
            //list_SP.Add(new SqlParameter("type", type));
            //list_SP.Add(new SqlParameter("To_Staff_ID", To_Staff_ID));

            //DbParameter[] sp = list_SP.ToArray();

            //IDataReader dr = conn.SelectSql("select top 1 id from [Notice_WX]  WITH(UPDLOCK, ROWLOCK)  where [Keyword1]=@Keyword1 and [type]=@type and [To_Staff_ID]=@To_Staff_ID  and datediff(minute,addtime,getdate())<=30 ");
            //if (!dr.Read())
            //{
            //    JObject json_post = new JObject();
            //    json_post["mbid"] = MB_ID;
            //    json_post["staff_id"] = To_Staff_ID;
            //    json_post["keyword1"] = Keyword1;
            //    json_post["keyword2"] = Keyword2;
            //    json_post["keyword3"] = Keyword3;
            //    json_post["keyword4"] = Keyword4;
            //    json_post["url"] = Url;
            //    json_post["First"] = First;
            //    json_post["type"] = type;
            //    result = PostJson_utf8(client, "http://172.16.41.41:81/api2/wx_msg_send2", json_post.ToString());
            //}
            //dr.Dispose();
            lock (o_wx)
            {
                //执行的代码块或者调用 其他方法
                (string open_id, string staff_name) = Get_Staff_Open_ID_name(To_Staff_ID);
                try
                {

                    //string open_id = Get_Staff_Open_ID(To_Staff_ID);

                    SqlParameter[] Par = new SqlParameter[] {
                     new SqlParameter("@First", First) ,
                     new SqlParameter("@Keyword1", Keyword1) ,
                     new SqlParameter("@Keyword2", Keyword2) ,
                     new SqlParameter("@Keyword3", Keyword3) ,
                     new SqlParameter("@Keyword4", Keyword4) ,
                     new SqlParameter("@open_id", open_id) ,
                     new SqlParameter("@staff_name", staff_name) ,
                     new SqlParameter("@Remark", Remark) ,
                     new SqlParameter("@Url", Url) , //点击消息访问的URL，为空时""，则不能点击。
                     new SqlParameter("@Content", "") ,  //不管它
                     new SqlParameter("@MB_ID", MB_ID) , //模板ID
                     new SqlParameter("@type", type) , // 消息类型 
                     new SqlParameter("@To_Staff_ID", To_Staff_ID) ,  //接收者 Staff表的ID，会自动获取表中的openid 。
                     new SqlParameter("@GetIP", "127.0.0.1") , //不管化
                     };




                    //查询表中是否已经有相同的发送消息队列，如果有重复的，则不再插入；

                    using (SqlConnection con = new SqlConnection(Conn.ConnString()))
                    {
                        con.Open();
                        using (SqlCommand com = new SqlCommand(" select top 1 id from [Notice_WX]  WITH(UPDLOCK, ROWLOCK)  where [Keyword1]=@Keyword1 and [type]=@type and [To_Staff_ID]=@To_Staff_ID  and datediff(minute,addtime,getdate())<=30 ", con))
                        {
                            if (Par != null) { com.Parameters.AddRange(Par.Select(x => ((ICloneable)x).Clone()).ToArray()); }
                            using (SqlDataAdapter sda = new SqlDataAdapter(com))
                            {
                                using (DataSet ds = new DataSet())
                                {
                                    sda.Fill(ds);
                                    if (sda.Fill(ds, "temptable") == 0)
                                    {
                                        ds.Tables.Add(new DataTable());
                                    }
                                    if (ds.Tables[0].Rows.Count == 0)
                                    {

                                        using (SqlCommand comm = new SqlCommand(" insert into [Notice_WX]  WITH(ROWLOCK)  ([First],[Keyword1],[Keyword2],[Keyword3],[Keyword4],[Remark] ,[Url],[Type],[MB_ID],[To_Staff_ID] , [staff_name] ,[open_id],[addip] , [status] ,[Send_Status]) values(@First , @Keyword1 , @Keyword2, @Keyword3 ,@Keyword4 ,@Remark , @Url ,@type ,@MB_ID, @To_Staff_ID , @staff_name ,@open_id , @GetIP , 0, '" + result + "') ; SELECT @@Identity", con))
                                        {
                                            if (Par != null) comm.Parameters.AddRange(Par.Select(x => ((ICloneable)x).Clone()).ToArray());
                                            //SqlDataReader dr = comm.ExecuteReader();
                                            int i = Convert.ToInt32(comm.ExecuteScalar());
                                            comm.Parameters.Clear();
                                            comm.Dispose();
                                        }

                                        //taskResult = Msg_Send(open_id, MB_ID, First, Keyword1, Keyword2, Keyword3, Remark, Url, Keyword4);
                                        //if (taskResult.IndexOf("\"ok\"") > 0)
                                        //{
                                        //    taskResult = "发送成功(" + taskResult + ")" + staff_name + open_id + ": <br/>keyword1:" + Keyword1 + "<br/>keyword2:" + Keyword2 + "<br/>keyword3:" + Keyword3 + "<br/>keyword5+" + Keyword4 + "<br/>url:" + Url;

                                        //    using (SqlCommand comm = new SqlCommand(" insert into [Notice_WX]  WITH(ROWLOCK)  ([First],[Keyword1],[Keyword2],[Keyword3],[Keyword4],[Remark] ,[Url],[Type],[MB_ID],[To_Staff_ID] , [staff_name] ,[open_id],[addip] , [status] ,[Send_Status]) values(@First , @Keyword1 , @Keyword2, @Keyword3 ,@Keyword4 ,@Remark , @Url ,@type ,@MB_ID, @To_Staff_ID , @staff_name ,@open_id , @GetIP , 1 ,'" + result + "') ;SELECT @@Identity", con))
                                        //    {
                                        //        if (Par != null) comm.Parameters.AddRange(Par.Select(x => ((ICloneable)x).Clone()).ToArray());
                                        //        //SqlDataReader dr = comm.ExecuteReader();
                                        //        int i = Convert.ToInt32(comm.ExecuteScalar());
                                        //        comm.Parameters.Clear();
                                        //        comm.Dispose();
                                        //    }

                                        //    //conn.InsertSql(" insert into [Notice_WX]  WITH(ROWLOCK)  ([First],[Keyword1],[Keyword2],[Keyword3],[Keyword4],[Remark] ,[Url],[Type],[MB_ID],[To_Staff_ID] , [staff_name] ,[open_id],[addip] , [status] ,[Send_Status]) values(@First , @Keyword1 , @Keyword2, @Keyword3 ,@Keyword4 ,@Remark , @Url ,@type ,@MB_ID, @To_Staff_ID , @staff_name ,@open_id , @GetIP , 1 ,'" + result + "') ", Par);

                                        //}
                                        //else
                                        //{
                                        //    taskResult = "发送失败(" + taskResult + ")" + staff_name + open_id + ": <br/>keyword1:" + Keyword1 + "<br/>keyword2:" + Keyword2 + "<br/>keyword3:" + Keyword3 + "<br/>keyword5+" + Keyword4 + "<br/>url:" + Url;

                                        //    using (SqlCommand comm = new SqlCommand(" insert into [Notice_WX]  WITH(ROWLOCK)  ([First],[Keyword1],[Keyword2],[Keyword3],[Keyword4],[Remark] ,[Url],[Type],[MB_ID],[To_Staff_ID] , [staff_name] ,[open_id],[addip] , [status] ,[Send_Status]) values(@First , @Keyword1 , @Keyword2, @Keyword3 ,@Keyword4 ,@Remark , @Url ,@type ,@MB_ID, @To_Staff_ID , @staff_name ,@open_id , @GetIP , 0, '" + result + "') ; SELECT @@Identity", con))
                                        //    {
                                        //        if (Par != null) comm.Parameters.AddRange(Par.Select(x => ((ICloneable)x).Clone()).ToArray());
                                        //        //SqlDataReader dr = comm.ExecuteReader();
                                        //        int i = Convert.ToInt32(comm.ExecuteScalar());
                                        //        comm.Parameters.Clear();
                                        //        comm.Dispose();
                                        //    }

                                        //    //conn.InsertSql(" insert into [Notice_WX]  WITH(ROWLOCK)  ([First],[Keyword1],[Keyword2],[Keyword3],[Keyword4],[Remark] ,[Url],[Type],[MB_ID],[To_Staff_ID] , [staff_name] ,[open_id],[addip] , [status] ,[Send_Status]) values(@First , @Keyword1 , @Keyword2, @Keyword3 ,@Keyword4 ,@Remark , @Url ,@type ,@MB_ID, @To_Staff_ID , @staff_name ,@open_id , @GetIP , 0, '" + result + "') ", Par);
                                        //}

                                        //result = taskResult;
                                    }

                                    com.Parameters.Clear();

                                    sda.Dispose();
                                    com.Dispose();
                                    con.Close();
                                    con.Dispose();

                                }
                            }

                        }

                    }

                }
                catch (Exception ex)
                {

                    Into_Blog("写入微信待发送列表出错: 内容如下： keyword1:" + Keyword1 + " <br/>keyword2:" + Keyword2 + "<br/>keyword3:" + Keyword3 + "<br/>keyword4:" + Keyword4 + "<br/>Remark:" + Remark + "<br/>发送给：" + staff_name + "(Staff_ID:" + To_Staff_ID + "。" + open_id + ")" + ex.ToString() + "<br/>返回结果 result: " + result, 1, "Notice_WX", 0);
                }
            }

            return result;
        }



        public void Into_Notice_WX222(string First, string type, string Keyword1, string Keyword2, string Keyword3, string Remark, string Url, string MB_ID, int To_Staff_ID, string Keyword4 = "")
        {
            try
            {

                (string open_id, string staff_name) = Get_Staff_Open_ID_name(To_Staff_ID);
                SqlParameter[] Par = new SqlParameter[] {
                    new SqlParameter("@First", First) ,
                    new SqlParameter("@Keyword1", Keyword1) ,
                    new SqlParameter("@Keyword2", Keyword2) ,
                    new SqlParameter("@Keyword3", Keyword3) ,
                    new SqlParameter("@Keyword4", Keyword4) ,
                    new SqlParameter("@Remark", Remark) ,
                    new SqlParameter("@open_id", open_id) ,
                    new SqlParameter("@staff_name", staff_name) ,
                    new SqlParameter("@Url", Url) ,
                    new SqlParameter("@Content", "") ,
                    new SqlParameter("@MB_ID", MB_ID) ,
                    new SqlParameter("@type", type) ,
                    new SqlParameter("@To_Staff_ID", To_Staff_ID) ,
                    new SqlParameter("@GetIP", "{\"ip\":\"127.0.0.1\"}") ,
                  };

                int Gas_Alert_Time = 10;
                IDataReader dr = conn.SelectSql("select top 1 * from [config] WITH(UPDLOCK)  where name='Gas_Alert_Time' order by id asc");
                if (dr.Read())
                {
                    Gas_Alert_Time = IsNumber(dr["value"].ToString()) ? int.Parse(dr["value"].ToString()) : 10;
                }
                dr.Close();
                dr.Dispose();

                //Into_Blog("写入微信待发送列表开始!" + title + content, 1, "Notice_WX", 0);

                dr = conn.SelectSql(" select top 1 * from [Notice_WX]  WITH(UPDLOCK)  where [First]=@First and [type]=@type  and [To_Staff_ID]=@To_Staff_ID and [Keyword1]=@Keyword1  and datediff(minute,addtime,getdate())<" + Gas_Alert_Time + " ", Par);
                if (!dr.Read())
                {
                    conn.InsertSql(" insert into [Notice_WX]  WITH(UPDLOCK)  ([First],[Keyword1],[Keyword2],[Keyword3],[Keyword4],[Remark] ,[Url],[Type],[MB_ID],[To_Staff_ID] , [staff_name], [open_id],[addip]) values(@First , @Keyword1 , @Keyword2, @Keyword3 ,@Keyword4 ,@Remark , @Url ,@type ,@MB_ID, @To_Staff_ID , @staff_name , @open_id , @GetIP ) ", Par);
                }
                dr.Close();
                dr.Dispose();
            }
            catch (Exception ex)
            {
                Into_Blog("写入微信待发送列表出错:" + ex.ToString() + "<br/><br/>First:" + First + "<br/>Keyword1:" + Keyword1 + "<br/>Keyword2:" + Keyword2 + "<br/>Keyword3:" + Keyword3 + "<br/>Remark:" + Remark, 1, "Notice_WX", 0);
            }
        }




        public string GetUrl_utf8(string _url)
        {
            //Stream _getUrl = WebRequest.Create(_url).GetResponse().GetResponseStream();

            //StreamReader _getContent = new StreamReader(_getUrl, Encoding.UTF8);

            //string _readContent = _getContent.ReadToEnd();
            ////string[] _s =  (_readContent).Split("{},".ToCharArray()).Distinct().ToArray();
            //_getUrl.Close();
            //_getContent.Close();


            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Add("User-Agent", "mozilla/6.0 (windows nt 11.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/111.0.0.0 safari/537.36 edg/109.0.1518.78");

            var response = client.GetAsync(_url).Result;

            Task<string> t = response.Content.ReadAsStringAsync();

            return t.Result.ToString();
        }


        public string PostJson_utf8(HttpClient client, string _url, string jsonContent)
        {
            // 1. 创建 HttpClient 实例
            // 2. 设置请求头（可选，但推荐设置 User-Agent）
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Add("User-Agent", "mozilla/6.0 (windows nt 11.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/111.0.0.0 safari/537.36 edg/109.0.1518.78");

            // 3. 准备要发送的 JSON 内容
            // 使用 StringContent 包装 JSON 字符串
            // 关键：指定 Content-Type 为 application/json 和编码为 UTF-8
            StringContent content = new StringContent(
                jsonContent,
                Encoding.UTF8,
                "application/json"
            );

            // 4. 执行 POST 请求并同步等待结果
            // 注意：GetAsync 替换为 PostAsync
            using var response = client.PostAsync(_url, content).Result;

            // 5. 读取响应内容并同步等待
            using Task<string> t = response.Content.ReadAsStringAsync();
            client.Dispose();
            // 6. 返回响应字符串
            return t.Result.ToString();
        }




        //获得时间相差的值
        public double Datediff(DateTime _str1, DateTime _str2, string Type = "m")
        {
            double temp = 0;
            //DateTime dt1 = Convert.ToDateTime("2007-3-24 11:29:12");
            //DateTime dt2 = Convert.ToDateTime("2007-2-24 10:29:12");
            TimeSpan ts = _str1 - _str2;  //dt1 - dt2;
            temp = ts.TotalMinutes;
            if (Type == "d") temp = ts.TotalDays;
            if (Type == "m") temp = ts.TotalMinutes;
            if (Type == "h") temp = ts.TotalHours;
            if (Type == "s") temp = ts.TotalSeconds;
            return temp;   //直接返回相差分钟数    if (ts.TotalMinutes >  60)  //是否相差60分钟  
                           //string timespan = "相差:"
                           //+ ts.Days.ToString() + "天"
                           //+ ts.Hours.ToString() + "小时"
                           //+ ts.Minutes.ToString() + "分钟"
                           //+ ts.Seconds.ToString() + "秒";
        }



        public string MakeRandString(int L)
        {
            char[] _array = "ABCDEFTHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxzy12345678900".ToCharArray();
            string _NewPassword = "";
            for (int i = 0; i < L; i++)
            {
                int p = MakeRand(0, _array.Length - 1);
                _NewPassword += _array[p];
            }

            return _NewPassword;
        }



        //备份和收缩数据库
        public void BackUp_DB(object sender, EventArgs e)
        {
            ConnOA2 conn = new();
            try
            {
                if (DateTime.Now.Hour > 6)  //当天时间大于早上6点
                {
                    //string upload_path = "D:\\wwwroot\\Back_SqlServer\\";
                    //string BackFileName = upload_path + "zty-oa_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + ".bak"; //备份路径和文件名
                    string DbName = "[zty_iot]";  //数据库名称
                    string DbLogName = "zty_iot_log";  //事务日志名称

                    //if (Directory.Exists(upload_path) == false)//如果不存在就创建upload_path文件夹
                    //{
                    //    Directory.CreateDirectory(upload_path);
                    //}

                    //ViewBag.TEMP += "间隔天数:" + Datediff(DateTime.Now, Back_Time, "d") + "<br/>";
                    if (DateTime.Now.Hour == 8 && DateTime.Now.Minute == 1)  //  判断 启动备份；
                    {
                        //ViewBag.TEMP += BackFileName + "<br/>";
                        Console.WriteLine("11");
                        conn.UpdataData("ALTER DATABASE " + DbName + " SET RECOVERY SIMPLE WITH NO_WAIT");
                        conn.UpdataData("ALTER DATABASE " + DbName + " SET RECOVERY SIMPLE --简单模式");
                        conn.UpdataData("DBCC SHRINKFILE (N'" + DbLogName + "' , 11, TRUNCATEONLY)");  //清空事务日志
                        conn.UpdataData("DBCC SHRINKDATABASE(" + DbName + ", 0)");  //收缩数据库
                        conn.UpdataData("ALTER DATABASE " + DbName + " SET RECOVERY FULL WITH NO_WAIT");
                        conn.UpdataData("ALTER DATABASE " + DbName + " SET RECOVERY FULL --还原为完全模式");

                        // 开始备份数据库
                        // int i = conn.UpdataData("BACKUP DATABASE " + DbName + " TO DISK = '" + BackFileName + "' WITH NOFORMAT, INIT, NAME = N'" + DbName + "-完整 数据库 备份', SKIP, NOREWIND, NOUNLOAD, STATS = 10");
                        //List<SqlParameter> list_SP = new();
                        //list_SP.Add(new SqlParameter("BackFileName", BackFileName));
                        //list_SP.Add(new SqlParameter("AddTime", DateTime.Now));
                        //SqlParameter[] sp = list_SP.ToArray();

                        //conn.UpdataData(" update [Config] set [Back_Time]=@AddTime where id=1 ", sp);

                        //int i2 = conn.InsertSql("insert into [DB_BackFileName] ([BackFileName],[AddTime]) values(@BackFileName , @AddTime )  ", sp);

                        //Into_Blog("系统自动备份数据库成功" + BackFileName, 1, "DB_BackFileName", i);

                    }


                }



            }
            catch (Exception ex)
            {
                Into_Blog("备份数据库失败," + ex.ToString(), 1, "mdf", 1);
            }
        }


        // 加密发送的信息
        [Obsolete]
        public string EncodeAES(string text, string key)
        {
            RijndaelManaged rijndaelCipher = new();
            rijndaelCipher.Mode = CipherMode.CBC;
            rijndaelCipher.Padding = PaddingMode.PKCS7;
            rijndaelCipher.KeySize = 128;
            rijndaelCipher.BlockSize = 128;
            byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
            byte[] keyBytes = new byte[16];
            int len = pwdBytes.Length;
            if (len > keyBytes.Length)
                len = keyBytes.Length;
            Array.Copy(pwdBytes, keyBytes, len);
            rijndaelCipher.Key = keyBytes;
            rijndaelCipher.IV = keyBytes;
            ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
            byte[] plainText = Encoding.UTF8.GetBytes(text);
            byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
            return Convert.ToBase64String(cipherBytes);
        }


    }






}
